import 'package:deepseek_client/extensions/StringExtensions.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'TypewriterText.dart';

class ResponseWidget extends StatefulWidget {
  final String text;
  final bool needType;

  const ResponseWidget({super.key, required this.text, required this.needType});

  @override
  State<StatefulWidget> createState() => _ResponseWidgetState();
}

class _ResponseWidgetState extends State<ResponseWidget> {
  final List<String> items = [];
  final ValueNotifier<bool> _startSecondNotifier = ValueNotifier(false);

  @override
  void initState() {
    super.initState();
    if(widget.text.contains('<think>') || widget.text.contains('</think>')){
      var split = widget.text.split('</think>');
      items.add(split[0].replaceAll('<think>', ''));
      items.add(split[1]);
      setState(() {});
      if(items[0].isBlank()){
        _startSecondNotifier.value = true;
      }
    }else{
      items.add(widget.text);
      _startSecondNotifier.value = true;
    }
  }

  @override
  void dispose() {
    super.dispose();
    _startSecondNotifier.dispose();
  }

  getContextMenu(context, editableTextState) {
    return AdaptiveTextSelectionToolbar.buttonItems(buttonItems: [
      ContextMenuButtonItem(
        onPressed: () {
          // 如果有选中文本，则复制选中的文本，否则复制整个文本
          if (editableTextState.textEditingValue.selection.isValid &&
              !editableTextState.textEditingValue.selection.isCollapsed) {
            editableTextState.copySelection(SelectionChangedCause.toolbar);
          } else {
            // 复制整个文本
            Clipboard.setData(
                ClipboardData(text: editableTextState.textEditingValue.text));
            editableTextState.hideToolbar();
          }
        },
        label: '复制',
      ),
      ContextMenuButtonItem(
        onPressed: () {
          editableTextState.selectAll(SelectionChangedCause.doubleTap);
          editableTextState.hideToolbar();
        },
        label: '全选',
      ),
    ], anchors: editableTextState.contextMenuAnchors);
  }

  @override
  Widget build(BuildContext context) {
    TextStyle responseStyle = const TextStyle(
        color: Colors.black, fontSize: 16, decoration: TextDecoration.none);

    return Padding(
      padding: const EdgeInsets.all(10),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if(items.isNotEmpty && items[0].isNotBlank())Container(
            width: double.infinity,
            margin: const EdgeInsets.only(bottom: 10),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: const Color(0xFFDDDDDD)
            ),
            padding: const EdgeInsets.all(16),
            child: SelectableTypewriterText(
              needType: widget.needType,
              textWidget: SelectableText(
                "以下是思考内容：\n${items[0]}",
                style: responseStyle,
                contextMenuBuilder: (context, editableTextState) {
                  return getContextMenu(context, editableTextState);
                },
              ),
              duration: const Duration(milliseconds: 20),
              onComplete: () {
                _startSecondNotifier.value = true;
              },
              onLineBreak: () async {

              },
            ),
          ),
          ValueListenableBuilder(
              valueListenable: _startSecondNotifier,
              builder: (context, start, child) {
                if (!start) {
                  return const SizedBox();
                }
                return SelectableTypewriterText(
                  needType: widget.needType,
                  textWidget: SelectableText(
                    items[1].replaceAll("\n", ""),
                    style: responseStyle,
                    contextMenuBuilder: (context, editableTextState) {
                      return getContextMenu(context, editableTextState);
                    },
                  ),
                  duration: const Duration(milliseconds: 20),
                  onComplete: () {

                  },
                  onLineBreak: () async {

                  },
                );
              })
        ],
      ),
    );
  }
}
